package org.lee.jfc.area;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.AreaRendererEndType;
import org.jfree.chart.renderer.category.AreaRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtils;

import javax.swing.*;
import java.awt.*;

/**
 * AreaChartDemo
 * 区域图
 *
 * @author dralee
 * @date 2021-12-29 15:13:13
 **/
public class AreaChartDemo extends JFrame {
    public AreaChartDemo() {
        initUI();
    }

    private void initUI() {
        CategoryDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        chartPanel.setBackground(Color.white);
        add(chartPanel);

        pack();
        setTitle("Line chart");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private JFreeChart createChart(CategoryDataset dataset) {
        JFreeChart chart = ChartFactory.createAreaChart("Oil consumption",
                "Time", "Thousands bbl/day", dataset,
                PlotOrientation.VERTICAL, false, true, true);
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        AreaRenderer renderer = (AreaRenderer) plot.getRenderer();
        renderer.setEndType(AreaRendererEndType.LEVEL);

        chart.setTitle(new TextTitle("Oil consumption", new Font("Serif", Font.BOLD, 18)));
        return chart;
    }

    private CategoryDataset createDataset() {
        double[][] data = new double[][]{
                {82501, 84026, 85002, 86218, 85521, 84213, 87138, 88158, 89319, 90781}
        };
        CategoryDataset dataset = DatasetUtils.createCategoryDataset(new String[]{"Oil"}, new String[]{"2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021"},
                data);
        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new AreaChartDemo().setVisible(true));
    }
}
